<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 对话界面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        #chat-container {
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 10px;
            height: 300px;
            overflow-y: auto;
        }

        input,
        button {
            padding: 5px;
            margin-right: 5px;
        }
    </style>
</head>

<body>
    <div id="chat-container"></div>
    <input type="text" id="user-input" placeholder="输入你的问题">
    <button onclick="sendMessage()">发送</button>

    <script>
        // 对话历史
        let history = [{
                "role": "system",
                "content": "你是一个智能助理，你的回答总是正确的、有用的和内容非常精简."
            },
            {
                "role": "user",
                "content": "请用中文进行自我介绍，要求不能超过5句话，总字数不超过100个字。"
            }
        ];

        async function sendMessage() {
            const userInput = document.getElementById('user-input').value;
            if (userInput.trim() === '') return;

            // 添加用户消息到历史记录
            history.push({
                "role": "user",
                "content": userInput
            });

            // 显示用户消息
            appendMessage('user', userInput);

            try {
                const response = await fetch('http://localhost:8000/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: "local-model",
                        messages: history,
                        temperature: 0.7,
                        stream: true
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                let assistantMessage = '';
                let partialChunk = '';

                while (true) {
                    const {
                        done,
                        value
                    } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = (partialChunk + chunk).split('\n');
                    partialChunk = lines.pop();

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            if (data === '[DONE]') break;

                            try {
                                const json = JSON.parse(data);
                                if (json.choices[0].delta.content) {
                                    const content = json.choices[0].delta.content;
                                    assistantMessage += content;
                                    appendMessage('assistant', content, true);
                                }
                            } catch (error) {
                                console.error('解析 JSON 出错:', error);
                            }
                        }
                    }
                }

                // 添加助理消息到历史记录
                history.push({
                    "role": "assistant",
                    "content": assistantMessage
                });

            } catch (error) {
                console.error('请求出错:', error);
                appendMessage('error', '请求出错，请稍后重试。');
            }

            // 清空输入框
            document.getElementById('user-input').value = '';
        }

        function appendMessage(role, content, isPartial = false) {
            const chatContainer = document.getElementById('chat-container');
            const messageDiv = document.createElement('div');
            messageDiv.className = role;
            if (role === 'user') {
                messageDiv.innerHTML = `<strong>你:</strong> ${content}`;
            } else if (role === 'assistant') {
                if (isPartial) {
                    messageDiv.innerHTML = content;
                    chatContainer.appendChild(messageDiv);
                } else {
                    messageDiv.innerHTML = `<strong>助理:</strong> ${content}`;
                    chatContainer.appendChild(messageDiv);
                }
            } else if (role === 'error') {
                messageDiv.innerHTML = `<strong>错误:</strong> ${content}`;
                messageDiv.style.color = 'red';
                chatContainer.appendChild(messageDiv);
            }
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 页面加载时自动发送自我介绍请求
        window.onload = sendMessage;
    </script>
</body>

</html>